package cn.itsource.campus.service.impl;

import cn.itsource.campus.domain.User;
import cn.itsource.campus.exception.AccountException;
import cn.itsource.campus.exception.PasswordException;
import cn.itsource.campus.mapper.UserMapper;
import cn.itsource.campus.service.IUserService;
import cn.itsource.campus.util.AjaxResult;
import cn.itsource.campus.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 校验用户名和密码
     * @param username 用户名
     * @param password 密码
     * @return
     * @throws IllegalArgumentException  如果用户名和密码为空或者为空字符串，我就抛出此异常
     * @throws AccountException  如果账号在数据库中不存在，我就抛出此异常
     * @throws PasswordException 如果密码和数据库中的密码不匹配，我就抛出此异常
     */
    @Override
    public AjaxResult checkUserByUsernameAndPassword(String username, String password) throws IllegalArgumentException,AccountException,PasswordException {
        if (username == null || "".equals(username)) {
            throw new IllegalArgumentException("用户名必填!!");
        }
        if (password == null || "".equals(password)) {
            throw new IllegalArgumentException("密码必填!!");
        }
        //根据用户名去数据库查询用户对象
        User user = userMapper.getUserByUsername(username);
        if (user == null) {
            throw new AccountException("账号不存在!!");
        }
        //如果密码不相等，则抛出异常
        if(!password.equals(user.getPassword())){
            throw new PasswordException("密码错误!!");
        }
        //随机产生一个字符串
        String token = UUID.randomUUID().toString();
        //存储到后端map集合中，相当于session一样
        UserContext.setLoginUser(token, user);
        return AjaxResult.ok("校验成功!",token);
    }

    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println(uuid.toString());

    }
}
